package org.example.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.utils.JwtUtil;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

// 拦截器
@Component // 通过这个将类注入ioc容器里面
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 接口进入之前，进行拦截
    /**
     * @param request 请求里面的所有信息
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求投获取token信息
        String token = request.getHeader("Authorization");

        // redis
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

        // token已修改或已过期
        if (operations.get(token) == null) {
            response.setStatus(401);
            return false;
        }

        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);

            ThreadLocalUtil.set(claims);
            // 放行
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            // 不放行
            return  false;
        }
    }

    // 请求结束
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
